package com.scs.application.core.msg.domain;

import com.google.common.collect.Lists;
import com.scs.application.core.msg.enums.MessageType;
import com.scs.application.core.msg.enums.ReceiverType;
import lombok.Data;
import lombok.experimental.Accessors;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 场景消息
 */
@Data
@Accessors(chain = true)
public class SceneMessage implements Serializable {

    /**
     * 场景标识
     */
    private String sceneCode;

    /**
     * 接收者。可以是用户ID、角色、部门，多个使用逗号隔开
     */
    private String receiver;

    /**
     * 接收者类型
     */
    private ReceiverType receiverType;


    private List<SceneMessageParam> params;

    /**
     * 业务类型
     */
    private String bizType;

    /**
     * 业务主键
     */
    private String bizKey;


    // 消息模板Id
    private String templateId;


    // 跳转地址
    private String toUrl;

    // 要发送的参数
    private List<WxMpTemplateData> data;

    /**
     * 适用于批量设置所有消息类型的参数
     *
     * @param params
     * @return
     */
    public SceneMessage params(Map<String, Object> params) {
        if (params == null) {
            return this;
        }
        this.params = Lists.newArrayListWithCapacity(params.size());
        for (String key : params.keySet()) {
            this.addParam(key, params.get(key), MessageType.all().toArray(new MessageType[0]));
        }
        return this;
    }

    /**
     * 适用于批量设置仅支持单种消息类型的参数
     *
     * @param params
     * @param messageType
     * @return
     */
    public SceneMessage params(Map<String, Object> params, MessageType messageType) {
        if (params == null) {
            return this;
        }
        this.params = Lists.newArrayListWithCapacity(params.size());
        for (String key : params.keySet()) {
            this.addParam(key, params.get(key), messageType);
        }
        return this;
    }

    public SceneMessage addParam(String name, Object value, MessageType... suitableMessageTypes) {
        if (params == null) {
            this.params = new ArrayList<>();
        }
        if(suitableMessageTypes == null){
            suitableMessageTypes = MessageType.all().toArray(new MessageType[0]);
        }
        this.params.add(new SceneMessageParam(name, value, suitableMessageTypes));
        return this;
    }


}
